/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import javax.swing.table.DefaultTableModel;
import resources.local_connection;

/**
 *
 * @author pato
 */
public final class Reingreso extends javax.swing.JFrame {

    /**
     * Creates new form Reingreso
     */
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String fechainicio = "", fechafinal = "";
    DefaultTableModel dtm;

    public Reingreso() {
        initComponents();
        dtm = (DefaultTableModel) Reingreso.jTable1.getModel();
        cargarDatos();
        finicial.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                cargarDatos();
            }
        });
        ffinal.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                cargarDatos();
            }
        });
        jTable1.removeColumn(jTable1.getColumnModel().getColumn(0));

    }

    public void cargarDatos() {
        dtm.setRowCount(0);
        fechainicio = (finicial.getDate() != null) ? sdf.format(finicial.getDate()) : sdf.format(new Date());
        fechafinal = (ffinal.getDate() != null) ? sdf.format(ffinal.getDate()) : "2050-12-30";
        String como = "'%" + txtBuscar.getText() + "%'";
        try {
            PreparedStatement ps = local_connection.getconnect().prepareStatement("select id, productos.id_producto, productos.nombre,"
                    + "productos.tipo, personas.nombre, (salida-entrada), retiro_producto.fecha from retiro_producto join "
                    + "productos on retiro_producto.id_producto = productos.id_producto join personas on"
                    + " retiro_producto.id_usuario = personas.id_persona where ((salida-entrada)>0) and "
                    + "(date(fecha) >='" + fechainicio + "' and date(fecha) <= '" + fechafinal
                    + "') and (productos.id_producto like " + como + " or productos.nombre like"
                    + como + " or personas.nombre like " + como + ")");
            ResultSet rs = ps.executeQuery();
            ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[dtm.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
            }
            //este bloque es para los especiales como el celular y el chip
            {
                ps = local_connection.getconnect().prepareStatement("select retiro_especial.clave, productos.id_producto, productos.nombre,"
                        + "productos.tipo, personas.nombre, 1, retiro_especial.salida from retiro_especial join "
                        + "especiales on especiales.clave = retiro_especial.clave join "
                        + "productos on especiales.id_producto = productos.id_producto join personas on"
                        + " retiro_especial.id_usuario = personas.id_persona where regreso = '0000-00-00 00:00:00' and "
                        + "(date(salida) >='" + fechainicio + "' and date(salida) <= '" + fechafinal
                        + "') and (productos.id_producto like " + como + " or productos.nombre like"
                        + como + " or personas.nombre like " + como + ")");
                rs = ps.executeQuery();
                //  System.out.println(ps);
                while (rs.next()) {
                    Object[] rows = new Object[dtm.getColumnCount()];
                    for (int i = 0; i < rows.length; i++) {
                        rows[i] = rs.getObject(i + 1);
                    }
                    data.add(rows);
                }
            }
            for (Object[] data1 : data) {
                dtm.addRow(data1);
            }

        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        ffinal = new com.toedter.calendar.JDateChooser();
        finicial = new com.toedter.calendar.JDateChooser();
        txtBuscar = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        jMenuItem1.setText("Regresar material");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "uno", "Id", "Nombre", "Tipo", "Responsable", "Cantidad", "Fecha"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setComponentPopupMenu(jPopupMenu1);
        jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(1).setMaxWidth(55);
            jTable1.getColumnModel().getColumn(5).setMaxWidth(55);
        }

        jLabel2.setText("Fecha Inicial:");

        jLabel3.setText("Fecha Final:");

        jLabel1.setText("Buscar:");

        finicial.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                finicialPropertyChange(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(finicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(ffinal, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(12, 12, 12)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(finicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ffinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 281, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void finicialPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_finicialPropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_finicialPropertyChange

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
int row = jTable1.getSelectedRow();
        if (row != -1) {
                row = jTable1.convertRowIndexToModel(row);
                if(dtm.getValueAt(row, 3).equals("Celular")||dtm.getValueAt(row, 3).equals("Chip")){
                    try {
                        PreparedStatement ps = local_connection.getconnect().prepareStatement("update retiro_especial set regreso = current_timestamp where clave = ?");
                        ps.setString(1,String.valueOf(dtm.getValueAt(row, 0)));
                        ps.execute();
                        cargarDatos();
                    } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);                    }
                }
                else{
                (new ReingresoPopUp(this, true, String.valueOf(dtm.getValueAt(row, 2)),
                        (int) dtm.getValueAt(row, 1), 
                        (Long.valueOf((long)dtm.getValueAt(row, 5))).floatValue(),
                        (String) dtm.getValueAt(row, 0))).setVisible(true);
                }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    /**
     * @param args the command line arguments
     *
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser ffinal;
    private com.toedter.calendar.JDateChooser finicial;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTable jTable1;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
